package com.example.othree.service.impl;

import com.example.othree.common.Email;
import com.example.othree.service.MailService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.mail.MailException;

@Service
public class MailServiceImpl implements MailService {
    /**
     * 注入邮件工具类
     */
    @Autowired(required = false)
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String UserName;

    @Override
    public boolean email(String email, String code) {

        Email emailObj = new Email();
        // 标题
        String subject = emailObj.getSubject();
        //正文内容
        String text = emailObj.getText()+code;

        //判断邮箱是否为空
        if (StringUtils.isEmpty(email)) {
            return false;
        }
        SimpleMailMessage msg = new SimpleMailMessage();
        //发送邮件的邮箱
        msg.setFrom(UserName);
        //发送到哪(邮箱)
        msg.setTo(email);
        //邮箱标题
        msg.setSubject(subject);
        //邮箱文本
        msg.setText(String.format(text, code));

        try {
            System.out.println("尝试发送");
            System.out.println(msg);
            javaMailSender.send(msg);
            System.out.println("已发送");
            System.out.println("msg=====>" + msg);
            return true;
        } catch (MailException ex) {
            ex.getMessage();
        }
        return false;
    }

}


